<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>我的</el-breadcrumb-item>
      <el-breadcrumb-item>个人信息</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" :body-style="{ padding: '0px' }" shadow="hover">
      <div slot="header" class="clearfix">
        <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload">
          <el-avatar v-if="user.photo" :src="'http://localhost:8080/'+user.photo"
                     class="avatar" :size="60"></el-avatar>
          <i v-else class="el-icon-plus avatar-uploader-icon el-phope"></i>
        </el-upload>

        <div>
          <el-button type="primary" @click="modifyInfo">修改信息</el-button>
          <el-button type="primary" @click="onRecharge">余额充值</el-button>
        </div>
      </div>
      <el-descriptions :column="1" size="medium" border>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-tickets"></i>
            用户名:
          </template>
          {{ user.username }}
        </el-descriptions-item>


        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-phone-outline"></i>
            电话:
          </template>
          {{ user.phone }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-money"></i>
            余额:
          </template>
          {{ user.wallet }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-news"></i>
            真实姓名:
          </template>
          {{ user.trueName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-s-check"></i>
            性别:
          </template>
          <span v-if="user.gender===1">男</span>
          <span v-if="user.gender===2">女</span>
        </el-descriptions-item>
      </el-descriptions>

    </el-card>

    <!--充值,保留一位小数-->
    <div>
      <el-dialog
          title="提示"
          :visible.sync="rechargeDiaVisible"
          width="30%"
          :before-close="handleRechargeClose">
        <span>充值金额: </span>
        <el-input v-model="money"
                  placeholder="请输入内容"
                  oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+2)}"
        ></el-input>
        <span slot="footer" class="dialog-footer">
            <el-button @click="rechargeDiaVisible = false">取 消</el-button>
            <el-button type="primary" @click="recharge">确 定</el-button>
          </span>
      </el-dialog>
    </div>

    <el-dialog
        title="修改信息"
        :visible.sync="modifyDiaVisible"
        width="30%"
        :before-close="handleClose">
      <el-form ref="user" :rules="rules" :model="userModify" label-width="80px">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="userModify.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input v-model="userModify.password" show-password></el-input>
        </el-form-item>

        <el-form-item prop="phone" label="电话">
          <el-input v-model="userModify.phone"></el-input>
        </el-form-item>
        <el-form-item  label="真实姓名">
          <el-input v-model="userModify.trueName"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userModify.gender">
            <el-radio :label='1'>男</el-radio>
            <el-radio :label='2'>女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">修改</el-button>
          <el-button @click="cancelModify">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Reset",
  inject: ['reload'],
  data() {
    // 电话号码验证
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100);
    };
    return {
      modifyDiaVisible: false,
      rechargeDiaVisible: false,
      money: 0,

      userModify: {
        id: null,
        username: "",
        password: "",
        phone: "",
        wallet: 0,
        trueName: "",
        gender: '',
        photo: ''
      },
      // 表单验证，需要在 el-form-item 元素中增加 prop 属性
      rules: {
        username: [
          {required: true, message: '账号不可为空', trigger: 'blur'},
          {
            min: 3,
            max: 10,
            message: '长度在3到10个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {required: true, message: '密码不可为空', trigger: 'blur'},
          {
            min: 6,
            max: 15,
            message: '长度在6到15个字符',
            trigger: 'blur'
          }
        ],
        phone: [
          {required: true, trigger: 'blur', validator: checkPhone}
        ]
      },
    };
  },

  computed: {
    user() {
      return this.$store.state.user;
    }
  },
  created() {

  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.modifyDiaVisible = false;
            // done();
          })
          .catch(_ => {
          });
    },
    handleRechargeClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.rechargeDiaVisible = false;
            // done();
          })
          .catch(_ => {
          });
    },
    // 显示修改页面
    modifyInfo: function () {
      // this.userModify=this.user; //不能这样，否则会改动this.user的属性
      this.userModify.id = this.user.id;
      this.userModify.username = this.user.username;
      this.userModify.password = this.user.password;
      this.userModify.phone = this.user.phone;
      this.userModify.trueName = this.user.trueName;
      this.userModify.gender = this.user.gender;
      this.modifyDiaVisible = true;
    },
    // 提交修改
    onSubmit() {
      this.$refs.user.validate((valid) => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: '/user/reset',
            data: {
              id: this.userModify.id,
              username: this.userModify.username,
              password: this.userModify.password,
              phone: this.userModify.phone,
              trueName: this.userModify.trueName,
              gender: this.userModify.gender
            }
          })
              .then(response => {
                if (response.data.success) {
                  this.$store.commit('setUser', response.data.user);
                  this.modifyDiaVisible = false;
                } else {
                  console.log("reset failure");
                }
              })
              .catch(error => {
                console.log(error);
              })
        } else {
          return this.$message.error("信息填写不完整！");
        }
      })

    },
    cancelModify() {
      this.modifyDiaVisible = false;
    },
    onRecharge() {
      this.rechargeDiaVisible = true;
    },
    // 余额充值
    recharge() {
      this.$axios.get("/user/recharge", {
        params: {
          id: this.user.id,
          value: this.money
        }
      })
          .then(response => {
            if (response.data.success) {
              this.$store.commit('setWallet', response.data.money);
              this.reload();
            } else {
              console.log(response.data.message);
            }
          })
          .catch(error => {
            console.log(error);
          })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt50M) {
        this.$message.error('上传图片大小不能超过 50MB!');
      }

      let formData = new FormData();//文件转换
      formData.append("file", file);
      formData.append("userId", this.$store.getters.uid)
      this.$axios.post('/user/savePhoto', formData, {"Content-Type": "multipart/form-data;charset=utf-8"})
          .then((res) => {

            this.$store.commit('setUser', res.data.user);

          }).catch((error) => {
        console.log(error)
      })

      return isJPG && isLt50M;
    }
  }
}
</script>

<style scoped>

.el-phope {
  height: 60px;
  width: 60px;
  line-height: 60px;
  display: block;
  border-radius: 50%;
  border: 1px dashed #d9d9d9;
}

.el-phope:hover {
  border-color: #409eff;
}
</style>
